package controllers

import (
	"encoding/xml"
	_ "fmt"
	"gitchina/CPTT4WeChat/models"
	"gitchina/CPTT4WeChat/models/event"
	"gitchina/CPTT4WeChat/models/handle"
	"gitchina/CPTT4WeChat/protobuf"
	"gitchina/CPTT4WeChat/util"
	"github.com/astaxie/beego"
	"github.com/golang/protobuf/proto"
)

type ApiController struct {
	beego.Controller
}

func init() {
	var wechat models.WeChat
	wechat.Init()
}

// @router /garden [get]
func (api *ApiController) GetGarden() {
	var g handle.Garden
	if proto, ok := g.GetByUid(api.GetString("id")); ok {
		api.Data["json"] = handle.Garden{Name: proto.GetName()}
		api.ServeJSON()
	} else {
		api.Ctx.ResponseWriter.WriteHeader(404)
	}
}

// @router / [get]
func (api *ApiController) CheckSignature() {
	var w models.WeChat
	signature := api.GetString("signature", "")
	ts := api.GetString("timestamp", "")
	nonce := api.GetString("nonce", "")
	echostr := api.GetString("echostr", "")
	if w.CheckSignature(signature, ts, nonce) {
		api.Ctx.WriteString(echostr)
	} else {
		api.Ctx.WriteString("")
	}
}

// @router /garden [post]
func (api *ApiController) AddOrUpdateGarden() {
	var g handle.Garden
	var info protobuf.Garden
	if err := proto.Unmarshal(api.Ctx.Input.RequestBody, &info); err == nil {
		g.AddOrUpdate(&info)
		api.Ctx.ResponseWriter.WriteHeader(200)
	} else {
		api.Ctx.ResponseWriter.WriteHeader(500)
		util.GetLogger().Error("[controller-AddOrUpdateGarden] error:%s", err.Error())
	}
}

// @router /user [post]
func (api *ApiController) AddOrUpdateUser() {
	var usr handle.User
	var batch protobuf.UserBatch
	if err := proto.Unmarshal(api.Ctx.Input.RequestBody, &batch); err == nil {
		usr.AddOrUpdate(&batch)
		api.Ctx.ResponseWriter.WriteHeader(200)
	} else {
		api.Ctx.ResponseWriter.WriteHeader(500)
		util.GetLogger().Error("[controller-AddOrUpdateUser] error:%s", err.Error())
	}
}

// @router /stats [post]
func (api *ApiController) AddOrUpdateStats() {
	var stats handle.Stats
	var batch protobuf.CheckInStatsBatch
	if err := proto.Unmarshal(api.Ctx.Input.RequestBody, &batch); err == nil {
		stats.AddOrUpdateCheckInStats(&batch)
	} else {
		api.Ctx.ResponseWriter.WriteHeader(500)
		util.GetLogger().Error("[controller-AddOrUpdateStats] error:%s", err.Error())
	}
}

// @router /data [post]
func (api *ApiController) AddOrUpdateCheckInOutData() {
	var stats handle.Stats
	var batch protobuf.CheckInDataBatch
	if err := proto.Unmarshal(api.Ctx.Input.RequestBody, &batch); err == nil {
		stats.AddOrUpdateCheckInData(&batch)
	} else {
		api.Ctx.ResponseWriter.WriteHeader(500)
		util.GetLogger().Error("[controller-AddOrUpdateCheckInOutData] error:%s", err.Error())
	}
}

// @router / [post]
func (api *ApiController) WeChatCall() {
	evt := event.ParseEvent(string(api.Ctx.Input.RequestBody))
	data, _ := xml.Marshal(evt.Handle())
	api.Ctx.WriteString(string(data))
}

// @router /welcome [get]
func (api *ApiController) Welcome() {
	api.Ctx.WriteString("Welcome")
}
